const { pool } = require('../config/db');

/**
 * 获取所有设备列表
 */
async function getAllDevices(req, res) {
  try {
    const [rows] = await pool.query('SELECT * FROM devices');
    
    // 转换为前端需要的格式
    const devices = rows.map(device => ({
      id: device.id,
      name: device.name,
      type: device.type,
      room: device.room,
      status: device.status === 1,
      connectionStatus: device.connection_status,
      device_id: device.device_id,
      ip_address: device.ip_address,
      mac_address: device.mac_address,
      user_id: device.user_id,
      lastUpdated: device.last_updated
    }));

    res.json({
      success: true,
      data: devices
    });
  } catch (error) {
    console.error('获取设备列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取设备列表失败',
      error: error.message
    });
  }
}

/**
 * 获取特定设备信息
 */
async function getDeviceById(req, res) {
  try {
    const { deviceId } = req.params;
    
    const [rows] = await pool.query('SELECT * FROM devices WHERE id = ?', [deviceId]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到'
      });
    }
    
    // 获取设备的详细参数
    const [paramRows] = await pool.query('SELECT * FROM device_parameters WHERE device_id = ?', [deviceId]);
    
    const device = rows[0];
    const deviceData = {
      id: device.id,
      name: device.name,
      type: device.type,
      room: device.room,
      status: device.status === 1,
      connectionStatus: device.connection_status,
      lastUpdated: device.last_updated,
      parameters: {}
    };
    
    // 添加设备参数
    paramRows.forEach(param => {
      deviceData.parameters[param.param_name] = param.param_value;
    });
    
    // 根据设备类型添加特定属性
    switch (device.type) {
      case 'air_conditioner':
        deviceData.mode = deviceData.parameters.mode || 'cool';
        deviceData.targetTemperature = parseFloat(deviceData.parameters.target_temperature) || 24;
        deviceData.fanSpeed = deviceData.parameters.fan_speed || 'auto';
        break;
      case 'humidifier':
        deviceData.targetHumidity = parseFloat(deviceData.parameters.target_humidity) || 50;
        deviceData.waterLevel = parseFloat(deviceData.parameters.water_level) || 100;
        break;
      case 'air_purifier':
        deviceData.mode = deviceData.parameters.mode || 'auto';
        deviceData.filterLife = parseFloat(deviceData.parameters.filter_life) || 100;
        break;
      case 'smart_window':
        deviceData.openPercentage = parseFloat(deviceData.parameters.open_percentage) || 0;
        deviceData.lockStatus = deviceData.parameters.lock_status === '1';
        break;
      case 'smart_curtain':
        deviceData.openPercentage = parseFloat(deviceData.parameters.open_percentage) || 0;
        break;
    }

    res.json({
      success: true,
      data: deviceData
    });
  } catch (error) {
    console.error('获取设备信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取设备信息失败',
      error: error.message
    });
  }
}

/**
 * 按房间获取设备
 */
async function getDevicesByRoom(req, res) {
  try {
    const { room } = req.params;
    
    const [rows] = await pool.query('SELECT * FROM devices WHERE room = ?', [room]);
    
    // 转换为前端需要的格式
    const devices = rows.map(device => ({
      id: device.id,
      name: device.name,
      type: device.type,
      status: device.status === 1,
      connectionStatus: device.connection_status,
      lastUpdated: device.last_updated
    }));

    res.json({
      success: true,
      data: devices
    });
  } catch (error) {
    console.error('获取房间设备失败:', error);
    res.status(500).json({
      success: false,
      message: '获取房间设备失败',
      error: error.message
    });
  }
}

/**
 * 按类型获取设备
 */
async function getDevicesByType(req, res) {
  try {
    const { type } = req.params;
    
    const [rows] = await pool.query('SELECT * FROM devices WHERE type = ?', [type]);
    
    // 转换为前端需要的格式
    const devices = rows.map(device => ({
      id: device.id,
      name: device.name,
      room: device.room,
      status: device.status === 1,
      connectionStatus: device.connection_status,
      lastUpdated: device.last_updated
    }));

    res.json({
      success: true,
      data: devices
    });
  } catch (error) {
    console.error('获取设备类型失败:', error);
    res.status(500).json({
      success: false,
      message: '获取设备类型失败',
      error: error.message
    });
  }
}

/**
 * 添加新设备
 */
async function addDevice(req, res) {
  try {
    const { name, type, room, device_id } = req.body;
    const userId = req.user ? req.user.id : null;
    
    if (!name || !type || !room) {
      return res.status(400).json({
        success: false,
        message: '设备名称、类型和房间是必需的'
      });
    }
    
    // 检查设备ID是否已存在
    if (device_id) {
      const [existingDevices] = await pool.query('SELECT * FROM devices WHERE device_id = ?', [device_id]);
      if (existingDevices.length > 0) {
        return res.status(400).json({
          success: false,
          message: '设备ID已存在'
        });
      }
    }
    
    // 构建SQL插入语句
    let sql = 'INSERT INTO devices (name, type, room, status, connection_status';
    let values = [name, type, room, 0, "disconnected"];
    let placeholders = '?, ?, ?, ?, ?';
    
    // 如果提供了设备ID，添加到SQL中
    if (device_id) {
      sql += ', device_id';
      placeholders += ', ?';
      values.push(device_id);
    }
    
    // 如果有用户ID，添加到SQL中
    if (userId) {
      sql += ', user_id';
      placeholders += ', ?';
      values.push(userId);
    }
    
    // 完成SQL语句
    sql += ') VALUES (' + placeholders + ')';
    
    // 插入新设备
    const [result] = await pool.query(sql, values);
    
    const deviceId = result.insertId;
    
    // 根据设备类型添加默认参数
    const defaultParams = [];
    
    switch (type) {
      case 'air_conditioner':
        defaultParams.push(
          [deviceId, 'mode', 'cool'],
          [deviceId, 'target_temperature', '24'],
          [deviceId, 'fan_speed', 'auto']
        );
        break;
      case 'humidifier':
        defaultParams.push(
          [deviceId, 'target_humidity', '50'],
          [deviceId, 'water_level', '100']
        );
        break;
      case 'air_purifier':
        defaultParams.push(
          [deviceId, 'mode', 'auto'],
          [deviceId, 'filter_life', '100']
        );
        break;
      case 'smart_window':
        defaultParams.push(
          [deviceId, 'open_percentage', '0'],
          [deviceId, 'lock_status', '0']
        );
        break;
      case 'smart_curtain':
        defaultParams.push(
          [deviceId, 'open_percentage', '0']
        );
        break;
    }
    
    // 批量插入默认参数
    if (defaultParams.length > 0) {
      await pool.query(
        'INSERT INTO device_parameters (device_id, param_name, param_value) VALUES ?',
        [defaultParams]
      );
    }

    res.status(201).json({
      success: true,
      message: '设备已添加',
      data: {
        id: deviceId,
        name,
        type,
        room,
        device_id,
        user_id: userId
      }
    });
  } catch (error) {
    console.error('添加设备失败:', error);
    res.status(500).json({
      success: false,
      message: '添加设备失败',
      error: error.message
    });
  }
}

/**
 * 更新设备信息
 */
async function updateDevice(req, res) {
  try {
    const { deviceId } = req.params;
    const { name, room, connection_status, status } = req.body;
    
    if (!name && !room && connection_status === undefined && status === undefined) {
      return res.status(400).json({
        success: false,
        message: '至少需要提供一个更新字段'
      });
    }
    
    // 构建更新查询
    let query = 'UPDATE devices SET ';
    const updateFields = [];
    const queryParams = [];
    
    if (name) {
      updateFields.push('name = ?');
      queryParams.push(name);
    }
    
    if (room) {
      updateFields.push('room = ?');
      queryParams.push(room);
    }
    
    if (connection_status !== undefined) {
      updateFields.push('connection_status = ?');
      queryParams.push(connection_status);
    }
    
    if (status !== undefined) {
      updateFields.push('status = ?');
      queryParams.push(status);
    }
    
    // 添加最后更新时间
    updateFields.push('last_updated = NOW()');
    
    query += updateFields.join(', ');
    query += ' WHERE id = ?';
    queryParams.push(deviceId);
    
    const [result] = await pool.query(query, queryParams);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到'
      });
    }

    res.json({
      success: true,
      message: '设备已更新',
      data: {
        id: parseInt(deviceId),
        name,
        room,
        connection_status,
        status
      }
    });
  } catch (error) {
    console.error('更新设备失败:', error);
    res.status(500).json({
      success: false,
      message: '更新设备失败',
      error: error.message
    });
  }
}

/**
 * 删除设备
 */
async function deleteDevice(req, res) {
  try {
    const { deviceId } = req.params;
    const userId = req.user ? req.user.id : null;
    
    // 检查设备是否存在以及是否属于当前用户
    const [devices] = await pool.query('SELECT * FROM devices WHERE id = ?', [deviceId]);
    
    if (devices.length === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到'
      });
    }
    
    const device = devices[0];
    
    // 检查设备是否属于当前用户（如果设备有用户ID且不匹配当前用户ID）
    if (device.user_id && userId && device.user_id !== userId) {
      return res.status(403).json({
        success: false,
        message: '无权删除此设备'
      });
    }
    
    // 首先删除设备参数
    await pool.query('DELETE FROM device_parameters WHERE device_id = ?', [deviceId]);
    
    // 然后删除设备
    const [result] = await pool.query('DELETE FROM devices WHERE id = ?', [deviceId]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到'
      });
    }

    res.json({
      success: true,
      message: '设备已删除',
      data: {
        id: parseInt(deviceId)
      }
    });
  } catch (error) {
    console.error('删除设备失败:', error);
    res.status(500).json({
      success: false,
      message: '删除设备失败',
      error: error.message
    });
  }
}

/**
 * 控制设备开关
 */
async function toggleDeviceStatus(req, res) {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    if (status === undefined) {
      return res.status(400).json({
        success: false,
        message: '状态参数是必需的'
      });
    }
    
    // 更新设备状态
    const [result] = await pool.query(
      'UPDATE devices SET status = ?, last_updated = NOW() WHERE id = ?',
      [status ? 1 : 0, id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到'
      });
    }

    res.json({
      success: true,
      message: `设备已${status ? '开启' : '关闭'}`,
      data: {
        id: parseInt(id),
        status: !!status
      }
    });
  } catch (error) {
    console.error('控制设备失败:', error);
    res.status(500).json({
      success: false,
      message: '控制设备失败',
      error: error.message
    });
  }
}

/**
 * 控制空调
 */
async function controlAirConditioner(req, res) {
  try {
    const { id } = req.params;
    const { mode, targetTemperature, fanSpeed } = req.body;
    
    // 验证设备类型
    const [deviceRows] = await pool.query(
      'SELECT * FROM devices WHERE id = ? AND type = "air_conditioner"',
      [id]
    );
    
    if (deviceRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '空调设备未找到'
      });
    }
    
    // 更新参数
    const updates = [];
    
    if (mode) {
      updates.push(pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "mode"',
        [mode, id]
      ));
    }
    
    if (targetTemperature !== undefined) {
      updates.push(pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "target_temperature"',
        [targetTemperature.toString(), id]
      ));
    }
    
    if (fanSpeed) {
      updates.push(pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "fan_speed"',
        [fanSpeed, id]
      ));
    }
    
    // 更新设备最后更新时间
    updates.push(pool.query(
      'UPDATE devices SET last_updated = NOW() WHERE id = ?',
      [id]
    ));
    
    await Promise.all(updates);

    res.json({
      success: true,
      message: '空调设置已更新',
      data: {
        id: parseInt(id),
        mode,
        targetTemperature,
        fanSpeed
      }
    });
  } catch (error) {
    console.error('控制空调失败:', error);
    res.status(500).json({
      success: false,
      message: '控制空调失败',
      error: error.message
    });
  }
}

/**
 * 控制加湿器
 */
async function controlHumidifier(req, res) {
  try {
    const { id } = req.params;
    const { targetHumidity } = req.body;
    
    // 验证设备类型
    const [deviceRows] = await pool.query(
      'SELECT * FROM devices WHERE id = ? AND type = "humidifier"',
      [id]
    );
    
    if (deviceRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '加湿器设备未找到'
      });
    }
    
    // 更新目标湿度
    if (targetHumidity !== undefined) {
      await pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "target_humidity"',
        [targetHumidity.toString(), id]
      );
    }
    
    // 更新设备最后更新时间
    await pool.query(
      'UPDATE devices SET last_updated = NOW() WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      message: '加湿器设置已更新',
      data: {
        id: parseInt(id),
        targetHumidity
      }
    });
  } catch (error) {
    console.error('控制加湿器失败:', error);
    res.status(500).json({
      success: false,
      message: '控制加湿器失败',
      error: error.message
    });
  }
}

/**
 * 控制空气净化器
 */
async function controlAirPurifier(req, res) {
  try {
    const { id } = req.params;
    const { mode } = req.body;
    
    // 验证设备类型
    const [deviceRows] = await pool.query(
      'SELECT * FROM devices WHERE id = ? AND type = "air_purifier"',
      [id]
    );
    
    if (deviceRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '空气净化器设备未找到'
      });
    }
    
    // 更新模式
    if (mode) {
      await pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "mode"',
        [mode, id]
      );
    }
    
    // 更新设备最后更新时间
    await pool.query(
      'UPDATE devices SET last_updated = NOW() WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      message: '空气净化器设置已更新',
      data: {
        id: parseInt(id),
        mode
      }
    });
  } catch (error) {
    console.error('控制空气净化器失败:', error);
    res.status(500).json({
      success: false,
      message: '控制空气净化器失败',
      error: error.message
    });
  }
}

/**
 * 控制智能窗户
 */
async function controlSmartWindow(req, res) {
  try {
    const { id } = req.params;
    const { openPercentage, lockStatus } = req.body;
    
    // 验证设备类型
    const [deviceRows] = await pool.query(
      'SELECT * FROM devices WHERE id = ? AND type = "smart_window"',
      [id]
    );
    
    if (deviceRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '智能窗户设备未找到'
      });
    }
    
    // 更新参数
    const updates = [];
    
    if (openPercentage !== undefined) {
      updates.push(pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "open_percentage"',
        [openPercentage.toString(), id]
      ));
    }
    
    if (lockStatus !== undefined) {
      updates.push(pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "lock_status"',
        [lockStatus ? '1' : '0', id]
      ));
    }
    
    // 更新设备最后更新时间
    updates.push(pool.query(
      'UPDATE devices SET last_updated = NOW() WHERE id = ?',
      [id]
    ));
    
    await Promise.all(updates);

    res.json({
      success: true,
      message: '智能窗户设置已更新',
      data: {
        id: parseInt(id),
        openPercentage,
        lockStatus
      }
    });
  } catch (error) {
    console.error('控制智能窗户失败:', error);
    res.status(500).json({
      success: false,
      message: '控制智能窗户失败',
      error: error.message
    });
  }
}

/**
 * 控制智能窗帘
 */
async function controlSmartCurtain(req, res) {
  try {
    const { id } = req.params;
    const { openPercentage } = req.body;
    
    // 验证设备类型
    const [deviceRows] = await pool.query(
      'SELECT * FROM devices WHERE id = ? AND type = "smart_curtain"',
      [id]
    );
    
    if (deviceRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '智能窗帘设备未找到'
      });
    }
    
    // 更新开启百分比
    if (openPercentage !== undefined) {
      await pool.query(
        'UPDATE device_parameters SET param_value = ? WHERE device_id = ? AND param_name = "open_percentage"',
        [openPercentage.toString(), id]
      );
    }
    
    // 更新设备最后更新时间
    await pool.query(
      'UPDATE devices SET last_updated = NOW() WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      message: '智能窗帘设置已更新',
      data: {
        id: parseInt(id),
        openPercentage
      }
    });
  } catch (error) {
    console.error('控制智能窗帘失败:', error);
    res.status(500).json({
      success: false,
      message: '控制智能窗帘失败',
      error: error.message
    });
  }
}

/**
 * 发现并连接设备
 */
async function discoverAndConnectDevice(req, res) {
  try {
    const deviceInfo = req.body;
    const userId = req.user ? req.user.id : null;
    
    // 验证必要的设备信息
    if (!deviceInfo.device_id || !deviceInfo.device_type || !deviceInfo.ip_address || !deviceInfo.mac_address) {
      return res.status(400).json({
        success: false,
        message: '设备信息不完整'
      });
    }
    
    // 检查设备是否已存在
    const [existingDevices] = await pool.query('SELECT * FROM devices WHERE device_id = ?', [deviceInfo.device_id]);
    
    let deviceId;
    
    if (existingDevices.length > 0) {
      // 设备已存在，更新连接状态
      deviceId = existingDevices[0].id;
      await pool.query(
        'UPDATE devices SET ip_address = ?, connection_status = "connected", status = 1, last_updated = NOW() WHERE id = ?',
        [deviceInfo.ip_address, deviceId]
      );
    } else {
      // 创建新设备
      let deviceName = '环境监测器';
      let deviceRoom = 'living_room';
      
      if (deviceInfo.device_type === 'environmental_monitor') {
        deviceName = '环境监测器';
      }
      
      // 构建SQL插入语句
      let sql = 'INSERT INTO devices (name, type, room, status, connection_status, device_id, ip_address, mac_address, ssid, rssi';
      let values = [deviceName, deviceInfo.device_type, deviceRoom, 1, "connected", deviceInfo.device_id, deviceInfo.ip_address, deviceInfo.mac_address, deviceInfo.ssid, deviceInfo.rssi];
      let placeholders = '?, ?, ?, ?, ?, ?, ?, ?, ?, ?';
      
      // 如果有用户ID，添加到SQL中
      if (userId) {
        sql += ', user_id';
        placeholders += ', ?';
        values.push(userId);
      }
      
      // 完成SQL语句
      sql += ') VALUES (' + placeholders + ')';
      
      // 插入新设备
      const [result] = await pool.query(sql, values);
      
      deviceId = result.insertId;
    }

    // 获取设备的完整信息
    const [rows] = await pool.query('SELECT * FROM devices WHERE id = ?', [deviceId]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到'
      });
    }
    
    const device = rows[0];
    const deviceData = {
      id: device.id,
      name: device.name,
      type: device.type,
      room: device.room,
      status: device.status === 1,
      connectionStatus: device.connection_status,
      device_id: device.device_id,
      ip_address: device.ip_address,
      mac_address: device.mac_address,
      ssid: device.ssid,
      rssi: device.rssi,
      user_id: device.user_id,
      lastUpdated: device.last_updated
    };

    res.json({
      success: true,
      message: '设备已成功连接',
      data: deviceData
    });
  } catch (error) {
    console.error('连接设备失败:', error);
    res.status(500).json({
      success: false,
      message: '连接设备失败',
      error: error.message
    });
  }
}

/**
 * 通用设备控制
 */
async function controlDevice(req, res) {
  try {
    const { deviceId } = req.params;
    const command = req.body;
    
    // 验证设备是否存在
    const [deviceRows] = await pool.query('SELECT * FROM devices WHERE id = ?', [deviceId]);
    
    if (deviceRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到'
      });
    }
    
    const device = deviceRows[0];
    
    // 处理操作命令
    const operation = command.operation;
    
    if (operation === 'on') {
      // 开启设备
      await pool.query(
        'UPDATE devices SET status = 1, last_updated = NOW() WHERE id = ?',
        [deviceId]
      );
      
      res.json({
        success: true,
        message: '设备已开启',
        data: {
          id: parseInt(deviceId),
          status: true
        }
      });
    } else if (operation === 'off') {
      // 关闭设备
      await pool.query(
        'UPDATE devices SET status = 0, last_updated = NOW() WHERE id = ?',
        [deviceId]
      );
      
      res.json({
        success: true,
        message: '设备已关闭',
        data: {
          id: parseInt(deviceId),
          status: false
        }
      });
    } else if (operation === 'adjust') {
      // 调整设备参数
      if (command.parameters) {
        const params = command.parameters;
        const updates = [];
        
        // 处理不同的参数
        for (const key in params) {
          updates.push(pool.query(
            'INSERT INTO device_parameters (device_id, param_name, param_value) VALUES (?, ?, ?) ' +
            'ON DUPLICATE KEY UPDATE param_value = VALUES(param_value)',
            [deviceId, key, params[key].toString()]
          ));
        }
        
        // 更新设备最后更新时间
        updates.push(pool.query(
          'UPDATE devices SET last_updated = NOW() WHERE id = ?',
          [deviceId]
        ));
        
        await Promise.all(updates);
        
        res.json({
          success: true,
          message: '设备参数已更新',
          data: {
            id: parseInt(deviceId),
            parameters: params
          }
        });
      } else {
        return res.status(400).json({
          success: false,
          message: '调整命令缺少参数'
        });
      }
    } else {
      return res.status(400).json({
        success: false,
        message: '不支持的操作命令'
      });
    }
  } catch (error) {
    console.error('控制设备失败:', error);
    res.status(500).json({
      success: false,
      message: '控制设备失败',
      error: error.message
    });
  }
}

/**
 * 通过MQTT发送命令控制设备
 */
async function sendMQTTCommand(req, res) {
  try {
    const { deviceId } = req.params;
    const command = req.body;
    
    // 验证设备是否存在
    const [deviceRows] = await pool.query('SELECT * FROM devices WHERE id = ? AND device_id IS NOT NULL', [deviceId]);
    
    if (deviceRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '设备未找到或设备ID为空'
      });
    }
    
    const device = deviceRows[0];
    const deviceUniqueId = device.device_id;
    
    // 构建MQTT主题
    const topic = `device/${deviceUniqueId}/control`;
    
    // 获取MQTT客户端
    const mqttClient = req.app.locals.mqttClient;
    
    if (!mqttClient || !mqttClient.connected) {
      return res.status(500).json({
        success: false,
        message: 'MQTT客户端未连接'
      });
    }
    
    // 发布消息
    mqttClient.publish(topic, JSON.stringify(command), { qos: 1 }, (error) => {
      if (error) {
        console.error('发布MQTT消息失败:', error);
        return res.status(500).json({
          success: false,
          message: '发布MQTT消息失败',
          error: error.message
        });
      }
      
      // 更新设备最后更新时间
      pool.query(
        'UPDATE devices SET last_updated = NOW() WHERE id = ?',
        [deviceId]
      ).catch(err => {
        console.error('更新设备最后更新时间失败:', err);
      });
      
      res.json({
        success: true,
        message: '命令已发送',
        data: {
          id: parseInt(deviceId),
          device_id: deviceUniqueId,
          topic: topic,
          command: command
        }
      });
    });
  } catch (error) {
    console.error('发送MQTT命令失败:', error);
    res.status(500).json({
      success: false,
      message: '发送MQTT命令失败',
      error: error.message
    });
  }
}

/**
 * 获取设备参数历史记录
 */
async function getDeviceParametersHistory(req, res) {
  try {
    const { deviceIds, limit = 5 } = req.query;
    const userId = req.user ? req.user.id : null;
    
    if (!userId) {
      return res.status(403).json({
        success: false,
        message: '未授权的请求'
      });
    }
    
    if (!deviceIds) {
      return res.status(400).json({
        success: false,
        message: '设备ID参数是必需的'
      });
    }
    
    // 解析设备ID列表
    const deviceIdArray = deviceIds.split(',').map(id => parseInt(id));
    
    // 验证这些设备是否属于当前用户
    const [userDevices] = await pool.query(
      'SELECT id FROM devices WHERE id IN (?) AND user_id = ?',
      [deviceIdArray, userId]
    );
    
    if (userDevices.length === 0) {
      return res.json({
        success: true,
        data: [],
        message: '未找到属于当前用户的设备'
      });
    }
    
    // 获取用户设备的ID列表
    const validDeviceIds = userDevices.map(device => device.id);
    
    // 获取设备参数历史记录
    const [paramRows] = await pool.query(`
      SELECT dp.*, d.name as device_name 
      FROM device_parameters dp
      JOIN devices d ON dp.device_id = d.id
      WHERE dp.device_id IN (?)
      ORDER BY dp.last_updated DESC
      LIMIT ?
    `, [validDeviceIds, parseInt(limit)]);
    
    res.json({
      success: true,
      data: paramRows
    });
  } catch (error) {
    console.error('获取设备参数历史记录失败:', error);
    res.status(500).json({
      success: false,
      message: '获取设备参数历史记录失败',
      error: error.message
    });
  }
}

module.exports = {
  getAllDevices,
  getDeviceById,
  getDevicesByRoom,
  getDevicesByType,
  addDevice,
  updateDevice,
  deleteDevice,
  toggleDeviceStatus,
  controlAirConditioner,
  controlHumidifier,
  controlAirPurifier,
  controlSmartWindow,
  controlSmartCurtain,
  discoverAndConnectDevice,
  controlDevice,
  getDeviceParametersHistory,
  sendMQTTCommand
};